package com.tanhua.dubbo.Api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 刘付磊
 * @date 2021/11/17 0017
 */
@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    @Override
    public void publish(Movement movement) {
        //1.保存动态详细
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //2.查询当前用户的好友数据
            timeLineService.TimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    //查询个人动态
    @Override
    public PageResult findAll(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pr = new PageResult(page,pagesize,0,movements);
        return pr;
    }

    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        //1.根据friendid查询时间线表
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = Query.query(criteria).
                skip((page-1)*pagesize).limit(pagesize).
                with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2.提取动态id
        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        Query query1 = Query.query(Criteria.where("id").in(movementId));
        return mongoTemplate.find(query1,Movement.class);
    }

    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        //1.创建统计对象，设计统计参数
         TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(pagesize));
        //2.调用mongoTemplate方法统计
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        //3.获取统计结果


        return aggregate.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> collect) {
        Query query = Query.query(Criteria.where("pid").in(collect));
        return mongoTemplate.find(query,Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }
}
